<!DOCTYPE html>
<html>
<head>
    <title>五运六气查询</title>
    <link rel="stylesheet" href="../static/css/ej.css">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> 
    <style>
        /* 响应式设计 */
        .stages-container {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            margin-top: 20px;
            width: 100%;
            box-sizing: border-box;
        }
        
        .stage-card {
            background-color: #f9f9f9;
            border-radius: 8px;
            padding: 15px;
            border: 1px solid #ddd;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            width: 100%;
            box-sizing: border-box;
        }
        
        .stage-header {
            background-color: #f3d9ea;
            color: rgb(124, 69, 115);
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 10px;
            text-align: center;
            font-weight: bold;
        }
        
        .stage-period {
            font-size: 14px;
            color: #666;
            margin-bottom: 10px;
        }
        
        .stage-section {
            margin-bottom: 15px;
        }
        
        .stage-section h4 {
            color: rgb(124, 69, 115);
            margin-bottom: 5px;
            font-size: 16px;
        }
        
        .stage-section ul {
            padding-left: 20px;
            margin: 0;
        }
        
        .stage-section li {
            margin-bottom: 3px;
            font-size: 14px;
        }
        
        .acupoint-item {
            background-color: #e8f4f8;
            padding: 5px;
            border-radius: 3px;
            margin-bottom: 5px;
        }
        
        /* 手机端适配 */
        @media (max-width: 768px) {
            .stages-container {
                grid-template-columns: 1fr;
            }
            
            .stage-card {
                padding: 10px;
            }
        }
        
        /* 体质页面专用样式 */
        .tizhi-container {
            display: flex;
            justify-content: center;
            width: 100%;
            padding: 0 20px;
        }
        
        .tizhi-card {
            background-color: #f9f9f9;
            border-radius: 12px;
            padding: 25px;
            border: 1px solid #ddd;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            width: 100%;
            max-width: 800px;
            box-sizing: border-box;
        }
        
        .tizhi-section {
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        
        .tizhi-section:last-child {
            border-bottom: none;
            margin-bottom: 0;
        }
        
        .tizhi-section h4 {
            color: rgb(124, 69, 115);
            margin-bottom: 12px;
            font-size: 18px;
            font-weight: bold;
        }
        
        .tizhi-content p {
            margin: 8px 0;
            font-size: 16px;
            line-height: 1.6;
            color: #444;
        }
        
        .tizhi-content .acupoint-item {
            background-color: #e8f4f8;
            padding: 8px 12px;
            border-radius: 6px;
            margin-bottom: 8px;
            border-left: 3px solid rgb(124, 69, 115);
        }
        
        /* 手机端体质页面适配 */
        @media (max-width: 768px) {
            .tizhi-card {
                padding: 15px;
                margin: 0 10px;
            }
            
            .tizhi-section h4 {
                font-size: 16px;
            }
            
            .tizhi-content p {
                font-size: 14px;
            }
        }
        
        /* 折叠展开功能 */
        .stage-content {
            max-height: 1000px;
            overflow: hidden;
            transition: max-height 0.3s ease;
        }
        
        .stage-content.collapsed {
            max-height: 0;
        }
        
        .toggle-btn {
            background: none;
            border: none;
            color: rgb(124, 69, 115);
            cursor: pointer;
            font-size: 14px;
            margin-top: 10px;
            display: none;
        }
        
        @media (max-width: 768px) {
            .toggle-btn {
                display: block;
            }
            
            .stage-content {
                max-height: 0;
            }
            
            .stage-content.expanded {
                max-height: 1000px;
            }
        }
        
        /* 防止水平溢出 */
        * {
            box-sizing: border-box;
        }
        
        html, body {
            width: 100%;
            overflow-x: hidden;
        }
    </style>
</head>
<body style="background-color:#fffbf6; margin: 0; padding: 0; overflow-x: hidden;">
    <div id="container" style="text-align:center;align-items: center; padding: 20px; max-width: 100%; box-sizing: border-box;">
        <h2 style="color:rgb(124, 69, 115); margin-bottom: 20px;">五运六气查询</h2>
        
        <div style="margin-bottom: 20px; max-width: 100%; box-sizing: border-box;">
            <label for="yearSelect" style="font-size: 16px; margin-right: 10px;">选择年份：</label>
            <select id="yearSelect" style="padding: 8px; font-size: 16px; border-radius: 4px; border: 1px solid #ccc; max-width: 100%;">
                <!-- 年份选项将通过JavaScript动态生成 -->
            </select>
        </div>
        
        <div style="margin-bottom: 20px; max-width: 100%; box-sizing: border-box;">
            <label style="font-size: 16px; margin-right: 15px;">
                <input type="radio" name="queryType" value="wuyun_liuqi" checked style="margin-right: 5px;">
                查看今年五运六气
            </label>
            <label style="font-size: 16px;">
                <input type="radio" name="queryType" value="birth_tizhi" style="margin-right: 5px;">
                查看出生年体质
            </label>
        </div>
        
        <div id="resultContainer" style="display: none; max-width: 100%; box-sizing: border-box;">
            <h3 style="color:rgb(124, 69, 115); margin-bottom: 20px;">查询结果</h3>
            <div id="stagesContainer" class="stages-container">
                <!-- 六个阶段的内容将通过JavaScript动态生成 -->
            </div>
        </div>
        
        <div id="loading" style="display: none; margin-top: 20px; max-width: 100%; box-sizing: border-box;">
            <div style="color:rgb(124, 69, 115);">正在查询中...</div>
        </div>
        
        <div id="errorContainer" style="display: none; margin-top: 20px; color: red; max-width: 100%; box-sizing: border-box;"></div>
    </div>
    <div style="text-align: center; font-size: 12px; color: #666; margin-top: 30px; padding: 10px; max-width: 100%; box-sizing: border-box;">
        有部分为AI生成内容，仅供参考。
    </div>
    
    <script src="../static/js/common.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化年份选择框
            initYearSelect();
            
            // 绑定年份选择变化事件
            document.getElementById('yearSelect').addEventListener('change', handleQuery);
            
            // 绑定查询类型变化事件
            document.querySelectorAll('input[name="queryType"]').forEach(radio => {
                radio.addEventListener('change', handleQuery);
            });
        });
        
        // 初始化年份选择框
        function initYearSelect() {
            const yearSelect = document.getElementById('yearSelect');
            const currentYear = new Date().getFullYear();
            
            // 生成1900-2100年的选项
            for (let year = 1900; year < 2100; year++) {
                const option = document.createElement('option');
                option.value = year;
                option.textContent = year + '年';
                
                // 默认选中今年
                if (year === currentYear) {
                    option.selected = true;
                }
                
                yearSelect.appendChild(option);
            }
        }
        
        // 处理查询请求
        function handleQuery() {
            const queryType = document.querySelector('input[name="queryType"]:checked').value;
            
            if (queryType === 'wuyun_liuqi') {
                queryWuyunLiuqi();
            } else if (queryType === 'birth_tizhi') {
                queryBirthTizhi();
            }
        }
        
        // 查询五运六气
        function queryWuyunLiuqi() {
            const selectedYear = document.getElementById('yearSelect').value;
            
            // 显示加载中
            document.getElementById('loading').style.display = 'block';
            document.getElementById('resultContainer').style.display = 'none';
            document.getElementById('errorContainer').style.display = 'none';
            
            // 发送请求到后端
            fetch('/get_wylq_advice', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ date: selectedYear })
            })
            .then(response => response.json())
            .then(data => {
                // 隐藏加载中
                document.getElementById('loading').style.display = 'none';
                
                if (data.res === 'ok') {
                    // 显示结果
                    console.log('data:',data);
                    document.getElementById('resultContainer').style.display = 'block';
                    displayStagesData(data.data);
                } else {
                    // 显示错误
                    document.getElementById('errorContainer').style.display = 'block';
                    document.getElementById('errorContainer').textContent = '查询失败：' + data.msg;
                }
            })
            .catch(error => {
                // 隐藏加载中
                document.getElementById('loading').style.display = 'none';
                
                // 显示错误
                document.getElementById('errorContainer').style.display = 'block';
                document.getElementById('errorContainer').textContent = '网络错误：' + error.message;
            });
        }

        // 查询出生年体质
        function queryBirthTizhi() {
            const selectedYear = document.getElementById('yearSelect').value;
            
            // 显示加载中
            document.getElementById('loading').style.display = 'block';
            document.getElementById('resultContainer').style.display = 'none';
            document.getElementById('errorContainer').style.display = 'none';
            
            // 发送请求到后端
            fetch('/get_wylq_advice', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ date: selectedYear })
            })
            .then(response => response.json())
            .then(data => {
                // 隐藏加载中
                document.getElementById('loading').style.display = 'none';
                
                if (data.res === 'ok') {
                    // 显示结果
                    console.log('birth tizhi data:', data.birth_tizhi);
                    document.getElementById('resultContainer').style.display = 'block';
                    displayBirthTizhiData(data.birth_tizhi);
                } else {
                    // 显示错误
                    document.getElementById('errorContainer').style.display = 'block';
                    document.getElementById('errorContainer').textContent = '查询失败：' + data.msg;
                }
            })
            .catch(error => {
                // 隐藏加载中
                document.getElementById('loading').style.display = 'none';
                
                // 显示错误
                document.getElementById('errorContainer').style.display = 'block';
                document.getElementById('errorContainer').textContent = '网络错误：' + error.message;
            });
        }

        // 显示出生年体质数据
        function displayBirthTizhiData(data) {
            const stagesContainer = document.getElementById('stagesContainer');
            stagesContainer.innerHTML = '';
            
            // 清理之前可能存在的年份信息div
            const existingYearInfo = document.getElementById('yearInfoDiv');
            if (existingYearInfo) {
                existingYearInfo.remove();
            }
            
            // 显示年份和五运六气信息
            const yearInfoDiv = document.createElement('div');
            yearInfoDiv.id = 'yearInfoDiv';
            yearInfoDiv.style.textAlign = 'center';
            yearInfoDiv.style.marginBottom = '20px';
            yearInfoDiv.style.padding = '15px';
            yearInfoDiv.style.backgroundColor = '#f0f8ff';
            yearInfoDiv.style.borderRadius = '8px';
            yearInfoDiv.style.border = '1px solid #d1e7ff';
            yearInfoDiv.innerHTML = `
                <h3 style="color: rgb(124, 69, 115); margin-bottom: 10px;">${data.year}年出生体质概况</h3>
                <p style="font-size: 16px; color: #333; margin: 5px 0;">
                    ${data.year}年为${data.ganzhi}年 · ${data.birth_wylq.keyun}
                </p>
                <p style="font-size: 16px; color: #333; margin: 5px 0;">
                    ${data.birth_wylq.sitian}司天 · ${data.birth_wylq.zaiquan}在泉
                </p>
            `;
            stagesContainer.parentNode.insertBefore(yearInfoDiv, stagesContainer);
            
            // 创建体质信息容器和卡片
            const tizhiContainer = document.createElement('div');
            tizhiContainer.className = 'tizhi-container';
            
            const tizhiCard = createTizhiCard(data.birth_tizhi);
            tizhiContainer.appendChild(tizhiCard);
            
            stagesContainer.appendChild(tizhiContainer);
            
            // 移除网格布局样式，确保卡片居中
            stagesContainer.style.display = 'block';
        }

        // 创建体质信息卡片
        function createTizhiCard(tizhiData) {
            const card = document.createElement('div');
            card.className = 'tizhi-card';
            
            // 病机核心 - 使用类似保养穴位的卡片样式
            const bingjiContent = tizhiData.病机核心.map(item => 
                `<div class="acupoint-item">${item}</div>`
            );
            const bingjiSection = createTizhiSection('病机核心', bingjiContent);
            
            // 体质特征 - 使用类似保养穴位的卡片样式
            const tizhiFeatures = [
                `体型：${tizhiData.体质.体型.join('，')}`,
                `面色：${tizhiData.体质.面色.join('，')}`,
                `功能倾向：${tizhiData.体质.功能倾向.join('，')}`,
                `心理优势：${tizhiData.体质.心理.优势.join('，')}`,
                `心理劣势：${tizhiData.体质.心理.劣势.join('，')}`
            ];
            const tizhiContent = tizhiFeatures.map(feature => 
                `<div class="acupoint-item">${feature}</div>`
            );
            const tizhiSection = createTizhiSection('体质特征', tizhiContent);
            
            // 敏感脏腑 - 使用类似保养穴位的卡片样式
            const sensitiveContent = tizhiData.敏感脏腑.map(item => 
                `<div class="acupoint-item">${item}</div>`
            );
            const sensitiveSection = createTizhiSection('敏感脏腑', sensitiveContent);
            
            // 易感疾病 - 使用类似保养穴位的卡片样式
            const diseaseContent = tizhiData.易感疾病.map(item => 
                `<div class="acupoint-item">${item}</div>`
            );
            const diseaseSection = createTizhiSection('易感疾病', diseaseContent);
            
            // 调理方案 - 饮食 - 使用类似保养穴位的卡片样式
            const dietContent = tizhiData.调理方案.饮食.map(item => 
                `<div class="acupoint-item">${item}</div>`
            );
            const dietSection = createTizhiSection('饮食调理', dietContent);
            
            // 调理方案 - 保养穴位
            const acupointsContent = tizhiData.调理方案.保养穴位.map(acupoint => 
                `<div class="acupoint-item">${acupoint.名称}：${acupoint.功效.join('，')}</div>`
            );
            const acupointsSection = createTizhiSection('保养穴位', acupointsContent);
            
            card.appendChild(bingjiSection);
            card.appendChild(tizhiSection);
            card.appendChild(sensitiveSection);
            card.appendChild(diseaseSection);
            card.appendChild(dietSection);
            card.appendChild(acupointsSection);
            
            return card;
        }

        // 创建体质信息区块
        function createTizhiSection(title, items) {
            const section = document.createElement('div');
            section.className = 'tizhi-section';
            
            const titleEl = document.createElement('h4');
            titleEl.textContent = title;
            
            const content = document.createElement('div');
            content.className = 'tizhi-content';
            
            if (Array.isArray(items)) {
                items.forEach(item => {
                    if (typeof item === 'string' && item.startsWith('<div')) {
                        // 如果是HTML内容（如穴位div），直接插入
                        content.innerHTML += item;
                    } else {
                        const p = document.createElement('p');
                        p.textContent = item;
                        content.appendChild(p);
                    }
                });
            } else {
                const p = document.createElement('p');
                p.textContent = items;
                content.appendChild(p);
            }
            
            section.appendChild(titleEl);
            section.appendChild(content);
            
            return section;
        }
        
        // 显示六个阶段的数据
        function displayStagesData(data) {
            const stagesContainer = document.getElementById('stagesContainer');
            stagesContainer.innerHTML = '';
            
            // 清理之前可能存在的年份信息div
            const existingYearInfo = document.getElementById('yearInfoDiv');
            if (existingYearInfo) {
                existingYearInfo.remove();
            }
            
            // 显示年份信息 - 在六张卡片上方
            const yearInfo = data.year_result;
            const yearInfoDiv = document.createElement('div');
            yearInfoDiv.id = 'yearInfoDiv'; // 添加ID以便后续清理
            yearInfoDiv.style.textAlign = 'center';
            yearInfoDiv.style.marginBottom = '20px';
            yearInfoDiv.style.padding = '15px';
            yearInfoDiv.style.backgroundColor = '#f0f8ff';
            yearInfoDiv.style.borderRadius = '8px';
            yearInfoDiv.style.border = '1px solid #d1e7ff';
            yearInfoDiv.innerHTML = `
                <h3 style="color: rgb(124, 69, 115); margin-bottom: 10px;">${yearInfo.year}年五运六气概况</h3>
                <p style="font-size: 16px; color: #333; margin: 5px 0;">
                    ${yearInfo.year}年为${yearInfo.tg}${yearInfo.dz}年 · ${yearInfo.keyun2}
                </p>
                <p style="font-size: 16px; color: #333; margin: 5px 0;">
                    ${yearInfo.sitian}司天 · ${yearInfo.zaiquan}在泉
                </p>
            `;
            stagesContainer.parentNode.insertBefore(yearInfoDiv, stagesContainer);
            
            const stages = data.health_advice.分段详情;
            const stageOrder = ['初之气', '二之气', '三之气', '四之气', '五之气', '终之气'];
            
            // 恢复网格布局样式
            stagesContainer.style.display = 'grid';
            
            stageOrder.forEach(stageKey => {
                const stage = stages[stageKey];
                const stageCard = createStageCard(stageKey, stage, data.year_result.this_year_stages.liuqi_stages[stageKey]);
                stagesContainer.appendChild(stageCard);
            });
        }
        
        // 创建阶段卡片
        function createStageCard(stageKey, stageData, period) {
            const card = document.createElement('div');
            card.className = 'stage-card';
            
            const header = document.createElement('div');
            header.className = 'stage-header';
            header.innerHTML = `${stageKey}（${stageData.主气} | ${stageData.客气}）`;
            
            const periodDiv = document.createElement('div');
            periodDiv.className = 'stage-period';
            periodDiv.textContent = `${period[0]} - ${period[1]}`;
            
            const content = document.createElement('div');
            content.className = 'stage-content';
            
            // 气候特征
            content.appendChild(createSection('气候特征', stageData.气候特征));
            
            // 调养方案 - 用逗号连接多条记录
            const dietText = stageData.调养方案.饮食.join('，');
            const livingText = stageData.调养方案.起居.join('，');
            const emotionText = stageData.调养方案.情志.join('，');
            
            const regimenContent = [
                `饮食：${dietText}`,
                `起居：${livingText}`,
                `情志：${emotionText}`
            ];
            content.appendChild(createSection('调养方案', regimenContent));
            
            // 保健穴位
            const acupointsContent = stageData.保健穴位.map(acupoint => 
                `${acupoint.名称}：${acupoint.功效}`
            );
            content.appendChild(createSection('保健穴位', acupointsContent));
            
            // 禁忌
            content.appendChild(createSection('禁忌', stageData.禁忌));
            
            
            // 折叠按钮（手机端）
            const toggleBtn = document.createElement('button');
            toggleBtn.className = 'toggle-btn';
            toggleBtn.textContent = '展开详情';
            toggleBtn.onclick = function() {
                content.classList.toggle('expanded');
                this.textContent = content.classList.contains('expanded') ? '收起详情' : '展开详情';
            };
            
            card.appendChild(header);
            card.appendChild(periodDiv);
            card.appendChild(content);
            card.appendChild(toggleBtn);
            
            return card;
        }
        
        // 创建信息区块
        function createSection(title, items) {
            const section = document.createElement('div');
            section.className = 'stage-section';
            
            const titleEl = document.createElement('h4');
            titleEl.textContent = title;
            
            const list = document.createElement('ul');
            items.forEach(item => {
                const li = document.createElement('li');
                li.textContent = item;
                list.appendChild(li);
            });
            
            section.appendChild(titleEl);
            section.appendChild(list);
            
            return section;
        }
        
    // 页面加载时自动查询一次
    window.addEventListener('load', queryWuyunLiuqi);
</script>


</body>
</html>
